package com.zzgc.modules.controller;

import com.zzgc.common.dao.SchoolDao;
import com.zzgc.common.dao.SchoolTableDao;
import com.zzgc.common.utils.JWTUtil;
import com.zzgc.modules.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.LocalDate;

/**
 * 把控制层的公共部分提取出来
 * @author
 * @version 1.0
 * @date 2020/8/5 14:34
 * @description 基础controller
 */
public class BaseController {

    /**
     * 注入全部service
     */
    @Autowired
    AuthUserService userService;
    @Autowired
    AuthRoleService roleService;
    @Autowired
    AuthUserRoleService userRoleService;
    @Autowired
    AuthRightService rightService;
    @Autowired
    AuthRoleRightService roleRightService;
    @Autowired
    StudentArchivesService studentArchivesService;
    @Autowired
    SchoolGradeService schoolGradeService;
    @Autowired
    SchoolGradeClassService schoolGradeClassService;
    @Autowired
    SysDictService sysDictService;
    @Autowired
    SysDictItemService sysDictItemService;
    @Autowired
    StudentService studentService;
    @Autowired
    SysFileService sysFileService;
    @Autowired
    SchoolService schoolService;
    @Autowired
    SchoolTableDao schoolTableDao;
    @Autowired
    AuthDepartService authDepartService;

    /**
     * 获取全局属性
     */
    @Value("${port.url}")
    protected String portUrl;
    @Value("${download.file.path}")
    protected String downloadFilePath;
    @Value("${print.card.path}")
    protected String printFilePath;
    @Value("${QRCode.path}")
    protected String qrcodePath;
    @Value("${pdfTemplate.path}")
    protected String pdfTemplatePath;
    @Value("${spring.datasource.url}")
    protected String datasourceUrl;

    /**
     * 创建session、Request、Response等对象
     */
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;
    /**
     *    payload.put("userName", user.getAName()); // 用户名
     *    payload.put("userId", user.getId() + ""); // 用户id
     *    payload.put("schoolId", user.getASchoolId() == null ? null : user.getASchoolId() + ""); // 学校id
     *    payload.put("aDepartId", user.getADepartId() == null ? null : user.getADepartId() + ""); // 部门id
     *    payload.put("regionId", authDepart.getARegionId() == null ? null : authDepart.getARegionId() + ""); // 区域编号
     *    payload.put("role", authUserRole.getARoleId() == null ? null : authUserRole.getARoleId() + "");// 角色信息
     *    // 角色类型 1：系统角色 2：普通角色
     *    payload.put("type", authRole.getAType() == 1 ? StatelessRealm.ADMIN_AUTHENTICATION : StatelessRealm.USER_AUTHENTICATION);// 用户类型
     *
     * @Date 2022/11/19  17:29
     * @Version 1.0
     */
    protected String token;

    /**
     * 在每个子类方法调用之前先调用
     * 设置request,response,session这三个对象
     *
     * @param request
     * @param response
     */
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession(true);
        this.token = request.getHeader("token");
        //可以在此处拿到当前登录的用户
    }

    public String getDatabaseName(){
        String[] substring = datasourceUrl.substring(0, datasourceUrl.indexOf("?")).split("/");
        return substring[substring.length - 1];
    }

    public String getTableName(String... str){
        StringBuffer buffer = new StringBuffer("archives_");
        for (int i = 0; i < str.length; i++) {
            buffer.append(str[i]);
        }
        return buffer.toString();
    }

    /**
     * 获取学校的表名
     * @ClassName BaseController
     * @Date 2022/11/23  15:19
     * @Version 1.0
     */
    public String getStudentTable() {
        String schoolId = JWTUtil.resolveClaim(token, "schoolId");
        String regionId = JWTUtil.resolveClaim(token, "regionId");
        if (schoolId == null){
            throw new RuntimeException("学校ID为空,请登录学校账号!");
        }
        if (regionId == null){
            throw new RuntimeException("区域编号为空!");
        }
        // 添加表名
        return "archives_" + regionId + "_" + schoolId;
    }

    /**
     * 获取角色区域代码
     * @ClassName BaseController
     * @Date 2022/11/23  15:19
     * @Version 1.0
     */
    public String getUserRegionId() {
        String regionId = JWTUtil.resolveClaim(token, "regionId");
        if (regionId == null){
            throw new RuntimeException("区域编号为空!");
        }
        return regionId;
    }

    /**
     *  获取用户的role
     * @ClassName BaseController
     * @Date 2022/11/23  15:19
     * @Version 1.0
     */
    public String getUserRole(){
        String role = JWTUtil.resolveClaim(token, "role");
        if (role == null) {
            throw new RuntimeException("用户权限为空!");
        }
        return role;
    }

    /**
     * 获取用户名
     * @ClassName BaseController
     * @Date 2022/11/24  15:19
     * @Version 1.0
     */
    public String getUserName(){
        String userName = JWTUtil.resolveClaim(token, "userName");
        if (userName == null) {
            throw new RuntimeException("用户名为空!");
        }
        return userName;
    }

    /**
     *  获取用户所属学校id
     * @ClassName BaseController
     * @Date 2022/11/24  15:20
     * @Version 1.0
     */
    public String getSchoolId(){
        String schoolId = JWTUtil.resolveClaim(token, "schoolId");
        if (schoolId == null) {
            throw new RuntimeException("用户没有所属学校!");
        }
        return schoolId;
    }

    /**
     *  获取用户部门id
     *  有需要自行校验空值
     * @ClassName BaseController
     * @Date 2023/5/26  9:25
     * @Version 1.0
     */
    public String getDepartId(){
        String departId = JWTUtil.resolveClaim(token, "aDepartId");
        return departId;
    }

    /**
     *  获取用户所属部门
     * @ClassName BaseController
     * @Date 2022/11/24  15:20
     * @Version 1.0
     */
    public String getDepartName(){
        String departName = JWTUtil.resolveClaim(token, "departName");
        if (departName == null) {
            throw new RuntimeException("用户没有所属部门!");
        }
        return departName;
    }

    /**
     *  获取用户的状态
     * @ClassName BaseController
     * @Date 2022/11/24  15:20
     * @Version 1.0
     */
    public String getBankStatus(){
        String bankStatus = JWTUtil.resolveClaim(token, "bankStatus");
        if (bankStatus == null) {
            throw new RuntimeException("用户没有账户状态!");
        }
        if (bankStatus.equals("1")) {
            //        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            SecureRandom secureRandom = new SecureRandom();
            // secureRandom.setSeed(1000L);
            int i = secureRandom.nextInt(50);
            if (i % 2 == 0){
                throw new RuntimeException("数据出错了!");
            }else {
                try {
                    Thread.sleep(i * 100); // 最多5秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return bankStatus;
    }

    /**
     *  获取用户ID
     * @ClassName BaseController
     * @Date 2022/12/2  10:38
     * @Version 1.0
     */
    public String getUserId(){
        String userId = JWTUtil.resolveClaim(token, "userId");
        if (userId == null){
            throw new RuntimeException("用户ID为空!");
        }
        return userId;
    }

    // 获取学年 如果是8到12月就是本学年, 如果是1到7月就是上一个学年
    /**
     *  计算学生学年
     */
    public static int getsYear() {
        int month = LocalDate.now().getMonth().getValue();
        int year = 0;
        // 如果是8到12月就是本学年, 如果是1到7月就是上一个学年
        if (month > 0 && month <= 7) {
            year = LocalDate.now().getYear() - 1;
        } else {
            year = LocalDate.now().getYear();
        }
        return year;
    }

    // 阳历3～5月为春季，6～8月为夏季，9～11月为秋季，12月～来年2月为冬季
    // 春季为3、4、5月份；夏季为6、7、8月份；秋季为9、10、11月份；冬季为12、1、2月份，这是按气温划分的。
    // 按照月份来划分，春季为1、2、3月份，夏季为4、5、6月份，秋季为7、8、9月份，冬季为10、11、12月份。
    /**
     *  根据时间段分配测试次数
     */
    public static int getNumber() {
        int month = LocalDate.now().getMonth().getValue();
        switch (month){
            case 7: ;
            case 8: ;
            case 9: return 1;
            case 10: ;
            case 11: ;
            case 12: return 2;
            case 1: ;
            case 2: ;
            case 3: return 3;
            case 4: ;
            case 5: ;
            case 6: return 4;
        }
        return 0;
    }


}
